<template>
  <div class="uploadFile-box">
    <div>
      <el-dialog
        title="上传体系LOGO图标"
        :visible.sync="dialogVisible"
        width="620px"
        :before-close="handleClose"
      >
        <div class="cropper-wrapper">
          <div class="cropper">
            <vueCropper
              class="cropper"
              ref="cropper"
              :img="option.img"
              :outputSize="option.size"
              :outputType="option.outputType"
              :info="true"
              :full="option.full"
              :canMove="option.canMove"
              :canMoveBox="option.canMoveBox"
              :original="option.original"
              :autoCrop="option.autoCrop"
              :fixed="option.fixed"
              :fixedNumber="option.fixedNumber"
              :centerBox="option.centerBox"
              :infoTrue="option.infoTrue"
              :fixedBox="option.fixedBox"
              :autoCropWidth="option.autoCropWidth"
              :autoCropHeight="option.autoCropHeight"
              :mode="option.mode"
              :fillColor="option.fillColor"
              @realTime="realTime"
            >
            </vueCropper>
          </div>
          <div>
            <h4>图样预览</h4>
            <div>
              <img
                :src="cropperPreviews"
                style="width:178px; height:34px; background:#2371c5;"
                alt="体系"
              />
              <div>请上传尺寸为178*34的图片</div>
              <div>格式为png、jpg、jpeg</div>
            </div>
            <!-- <div>
              <img
                :src="cropperPreviews"
                style="width:104px; height:16px;background:#2371c5;"
                alt="体系"
              />
              <div>104*16</div>
            </div> -->
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="submit" @click="finish" type="primary"
            >确 定</el-button
          >
          <el-upload
            class="dialog-upload"
            action="#"
            :show-file-list="false"
            accept=".jpg,.jpeg,.png"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
            fit="fill"
          >
            <el-button :loading="cropperLoading">
              重新上传
            </el-button>
          </el-upload>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 上传限制
import {fileUpload} from '../../const/api_staffCenter.js'
const updLimit = '.png,.jpg'
export default {
  name: 'cropperupload',
  props: {},
  data() {
    return {
      dialogVisible: false,
      uploadUrl: fileUpload,
      updImageUrl1: '', //正面
      updImageUrl2: '', //反面
      updLimit,
      // 上传属性
      imgAttr: {},
      cropperLoading: false,
      cropperPreviews: '',
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: 'png', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 178, // 默认生成截图框宽度
        autoCropHeight: 34, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [178, 34], // 截图框的宽高比例
        // full: true, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        fillColor: '#fff', // 颜色
        mode: 'cover' // cover  图片铺满容器
      }
    }
  },
  methods: {
    showDialog() {
      this.dialogVisible = true
    },
    handleAvatarSuccess(res, file) {
      this.$emit('uploadSuccess', file)
    },
    // 上传规则
    beforeAvatarUpload(file) {
      const isFormat = updLimit.includes(
        file.name.replace(/.+\./, '').toLowerCase()
      )
      if (!isFormat) {
        this.$message.error('上传证照只能是JPG、PNG格式!')
        return false
      }
      // 限制大小
      const isLimit = file.size / 1024 / 1024 < 11
      if (!isLimit) {
        this.$message.error('上传证照大小不能超过 10MB!')
        return false
      }
      this.file2base64(file)
    },
    // 获取图片宽高
    createReader(file, whenReady) {
      var reader = new FileReader()
      reader.onload = function(evt) {
        var image = new Image()
        image.onload = function() {
          var width = this.width
          var height = this.height
          if (whenReady) whenReady(width, height)
        }
        image.src = evt.target.result
      }
      reader.readAsDataURL(file)
    },
    // file类型文件 转base64文件类型
    file2base64(file) {
      var reader = new FileReader()
      reader.readAsDataURL(file)
      var self = this
      reader.onload = function(e) {
        // 图片base64化
        let newUrl = this.result //图片路径
        self.$nextTick(() => {
          self.pageImage = newUrl
          self.option.img = newUrl
          self.dialogVisible = true
        })
      }
    },
    finish() {
      this.$refs.cropper.getCropData(data => {
        // base64Toblob
        var arr = data.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        let theBlob = new Blob([u8arr], {type: mime})
        let file = new File([theBlob], 'proFileCover.png', {
          type: theBlob.type,
          lastModified: Date.now()
        })
        this.toRequest(file)
      })
    },
    toRequest(data) {
      // 发起请求
      let fd = new FormData()
      fd.append('file', data)
      this.$axios({
        method: 'post',
        url: fileUpload,
        headers: {'Content-Type': 'multipart/form-data'},
        data: fd
      }).then(res => {
        this.$emit('cropperSubmit', res, 'img')
        this.dialogVisible = false
      })
    },
    // base64实时预览
    realTime(data) {
      this.$refs.cropper.getCropData(data => {
        this.cropperPreviews = data
      })
    },
    handleClose() {
      this.dialogVisible = false
    }
  }
}
</script>
<style scoped lang="less">
.uploadFile-box {
  .dialog-footer {
    display: flex;
    .submit {
      margin-right: 15px;
    }
  }

  .cropper-wrapper {
    display: flex;
    .cropper {
      width: 350px;
      height: 240px;
      text-align: center;
      margin-right: 20px;
    }
  }

  .btnGroup {
    float: right;
    margin-top: 10px;
    margin-right: 15px;
  }
}
</style>
